<template>
  <div style="display: flex; height: 600px;">
    <!-- 左侧按钮列表 -->
    <div style="width: 200px; padding: 20px; background: #f5f5f5; border-right: 1px solid #ddd;">
      <h3>可拖拽按钮</h3>
      <div
        v-for="btn in dragButtons"
        :key="btn.value"
        class="drag-btn"
        draggable="true"
        @dragstart="onDragStart($event, btn)"
        :style="buttonStyle"
      >
        {{ btn.label }}
      </div>
    </div>
    <!-- 右侧富文本编辑器 -->
    <div style="flex: 1; padding: 0 20px;">
      <Editor
        v-model="content"
        :init="init"
        id="basic-example"
        @init="onEditorInit"
      />
    </div>

    <!-- 简易弹窗 -->
    <teleport to="body">
      <div v-if="showModal" class="modal-mask">
        <div class="modal">
          <h3>请选择替换内容</h3>
          <ul>
            <li
              v-for="item in options"
              :key="item.value"
              @click="selectOption(item)"
              style="padding: 8px; cursor: pointer; border-bottom: 1px solid #eee;"
            >
              {{ item.label }}
            </li>
          </ul>
          <button @click="showModal = false" style="margin-top: 10px;">取消</button>
        </div>
      </div>
    </teleport>
  </div>
  <button @click="gainContent">获取内容</button>
</template>

<script setup lang="ts">
import { onMounted, onBeforeUnmount, ref, computed, nextTick, watchEffect } from 'vue'
import Editor from '@tinymce/tinymce-vue'
import tinymce from 'tinymce/tinymce'
import 'tinymce/themes/silver/theme'
import 'tinymce/icons/default'
import 'tinymce/models/dom'
// 插件（同你原有）
import 'tinymce/plugins/preview'
import 'tinymce/plugins/searchreplace'
import 'tinymce/plugins/autolink'
import 'tinymce/plugins/directionality'
import 'tinymce/plugins/visualblocks'
import 'tinymce/plugins/visualchars'
import 'tinymce/plugins/fullscreen'
import 'tinymce/plugins/image'
import 'tinymce/plugins/link'
import 'tinymce/plugins/media'
import 'tinymce/plugins/code'
import 'tinymce/plugins/codesample'
import 'tinymce/plugins/table'
import 'tinymce/plugins/charmap'
import 'tinymce/plugins/pagebreak'
import 'tinymce/plugins/nonbreaking'
import 'tinymce/plugins/insertdatetime'
import 'tinymce/plugins/advlist'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/wordcount'
import 'tinymce/plugins/autosave'
import 'tinymce/plugins/emoticons/plugin.min'
import 'tinymce/plugins/emoticons/js/emojis.min'
import 'tinymce/plugins/anchor'

// 拖拽按钮数据
const dragButtons = ref([
  { label: '姓名', value: 'name' },
  { label: '电话', value: 'phone' },
  { label: '邮箱', value: 'email' },
  { label: '地址', value: 'address' }
])

// 替换选项
const options = ref([
  { label: '张三', value: 'zhangsan' },
  { label: '李四', value: 'lisi' },
  { label: '北京市', value: 'beijing' },
  { label: '13800138000', value: '13800138000' },
  { label: 'test@example.com', value: 'test@example.com' }
])

// 当前点击的按钮元素（用于替换）
const clickedButton = ref<HTMLElement | null>(null)
const showModal = ref(false)

// 按钮样式（保持一致）
const buttonStyle:any = {
  display: 'inline-block',
  padding: '6px 12px',
  margin: '5px 0',
  background: '#007bff',
  color: '#fff',
  border: 'none',
  borderRadius: '4px',
  cursor: 'move',
  fontSize: '14px',
  textAlign: 'center'
}

// 当前编辑器实例
let editorInstance: any = null

// 编辑器初始化回调
const onEditorInit = (evt: any, editor: any) => {
  editorInstance = editor
  setupButtonClickListener(editor)
}

// 设置按钮点击监听（事件代理）
const setupButtonClickListener = (editor: any) => {
  const body = editor.getBody()
  body.addEventListener('click', (e: MouseEvent) => {
    console.log('e',e)
    const target = e.target as HTMLElement
    if (target.classList.contains('draggable-button')) {
      clickedButton.value = target
      showModal.value = true
    }
  })
}

// 拖拽开始
const onDragStart = (event: DragEvent, btn: { label: string; value: string }) => {
  if (!event.dataTransfer) return
  event.dataTransfer.setData('text/plain', JSON.stringify(btn))
  // 可选：设置拖拽反馈样式
  const dragImg = document.createElement('div')
  dragImg.innerText = btn.label
  dragImg.style.padding = '6px 12px'
  dragImg.style.background = '#007bff'
  dragImg.style.color = '#fff'
  dragImg.style.borderRadius = '4px'
  dragImg.style.fontSize = '14px'
  dragImg.style.display = 'inline-block'
  document.body.appendChild(dragImg)
  event.dataTransfer.setDragImage(dragImg, 20, 20)
  setTimeout(() => document.body.removeChild(dragImg), 0)
}

// 选择替换内容
const selectOption = (item: { label: string; value: string }) => {
  if (!clickedButton.value || !editorInstance) return

  // 创建红色文本
  const span = document.createElement('span')
  span.style.color = 'red'
  span.textContent = item.label

  // 替换按钮
  clickedButton.value.replaceWith(span)

  // 触发 change 事件
  editorInstance.fire('input')
  editorInstance.fire('change')

  // 关闭弹窗
  showModal.value = false
  clickedButton.value = null
}

// 编辑器内容
const content = ref('')

// tinymce key
// const apiKey = ref('jmo5tbgjyyzxnk9rv18wktvly6sts1k4d0mq5dxzamxvox09')

// init 配置
const init = computed(() => ({
  selector: '#basic-example',
  skin_url: '/tinymce/skins/ui/oxide',
  language_url: '/tinymce/langs/zh-Hans.js',
  language: 'zh-Hans',
  placeholder: '拖拽左侧按钮到此处...',
  min_height: 600,
  width: '100%',
  resize: 'both',
  branding: false,
  statusbar: true,
  highlight_on_focus: true,
  promotion: false,
  font_size_formats: '10px 11px 12px 14px 16px 18px 20px 24px 36px',
  content_style: 'p, div {font-size: 14px; margin: 0; padding: 0;}',
  content_css: '/tinymce/skins/content/default/content.css',
  plugins: 'preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media code codesample table charmap pagebreak nonbreaking anchor insertdatetime advlist lists wordcount autosave emoticons',
  toolbar: 'undo redo | blocks fontsize | bold italic | alignleft aligncenter alignright | bullist numlist | link image media | code | fullscreen',
  removed_menuitems: 'newdocument codesample anchor code fullscreen fontfamily fontsize',
  paste_data_images: true,
  paste_webkit_styles: 'all',
  paste_merge_formats: true,
  file_picker_types: 'media',
  init_instance_callback: (editor: any) => {
    console.log('Editor 初始化完成')
    setupButtonClickListener(editor)
  },
  images_upload_handler: (blobInfo: any, _progress: Function) =>
      new Promise((resolve) => {
        const formData = new FormData()
        //   formData.append('file', blobInfo.blob(), blobInfo.filename())
        formData.append('file', blobInfo.blob())
        let reader = new FileReader() // 本地预览
        reader.readAsDataURL(blobInfo.blob())
        reader.onloadend = function () {
          const imgbase64 = reader.result as string
          // 请求成功之后调用 resolve
          resolve(imgbase64)
        }
      }),
  // 允许拖拽插入
  setup: (editor: any) => {
    editor.on('drop', (e: DragEvent) => {
      if (!e.dataTransfer) return
      const data = e.dataTransfer.getData('text/plain')
      try {
        const btn = JSON.parse(data)
        e.preventDefault()
        // 构造带样式的按钮 HTML
        const buttonHtml = `
          <button type="button"
            class="draggable-button"
            style="
              display: inline-block;
              padding: 6px 12px;
              margin: 0 2px;
              background: #007bff;
              color: #fff;
              border: none;
              border-radius: 4px;
              cursor: pointer;
              font-size: 14px;
              text-align: center;
            "
          >
            ${btn.label}
          </button>
        `

        editor.insertContent(buttonHtml)
      } catch (err) {
        console.error('拖拽数据解析失败', err)
      }
    })

    // 阻止默认拖拽行为，显示提示
    editor.on('dragover', (e: DragEvent) => {
      e.preventDefault()
    })
  }
}))

// 组件销毁
onBeforeUnmount(() => {
  if (tinymce.activeEditor) {
    tinymce.activeEditor.destroy()
  }
})

// 同步内容到父组件
watchEffect(() => {
  if (content.value !== undefined) {
    // emits('update:value', content.value) // 如果你需要 emit
  }
})
let gainContent = ()=>{
  console.log('获取到的内容',content.value)
}
</script>

<style scoped>
.drag-btn {
  cursor: move;
  user-select: none;
}

.modal-mask {
  position: fixed;
  z-index: 1000;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal {
  background: white;
  padding: 20px;
  border-radius: 8px;
  width: 300px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.modal ul {
  list-style: none;
  padding: 0;
  max-height: 200px;
  overflow-y: auto;
}

.modal li:hover {
  background: #f0f0f0;
}
</style>

<style>
/* 防止编辑器内部按钮被选中时样式错乱 */
.tox.tox-tinymce {
  max-width: 100%;
}

/* 确保按钮在编辑器内可点击 */
.tox-edit-area__iframe {
  pointer-events: auto !important;
}
</style>